﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace AppDesigner.Helper
{
    public static class ItemsControlExtensions
    {
        public static UIElement GetItemContainer(this ItemsControl itemsControl, UIElement child)
        {
            Type containerType = GetItemContainerType(itemsControl);
            if (containerType != null)
            {
                return (UIElement)child.GetVisualAncestor(containerType);
            }
            return null;
        }

        private static Type GetItemContainerType(ItemsControl itemsControl)
        {
            if (itemsControl.Items.Count > 0)
            {
                IEnumerable<ItemsPresenter> itemsPresenters = itemsControl.GetVisualDescendents<ItemsPresenter>();
                foreach (ItemsPresenter itemsPresenter in itemsPresenters)
                {
                    DependencyObject panel = VisualTreeHelper.GetChild(itemsPresenter, 0);
                    DependencyObject itemContainer = VisualTreeHelper.GetChild(panel, 0);
                    if (itemContainer != null && itemsControl.ItemContainerGenerator.IndexFromContainer(itemContainer) != -1)
                    {
                        return itemContainer.GetType();
                    }
                }
            }

            return null;
        }

      
    }
}
